import api from '@h5app/sheep/api'
import { acceptHMRUpdate, defineStore } from 'pinia'
import { ref } from 'vue'

export type UnwrapPromise<T> = T extends Promise<infer U> ? U : T
export type ResultType = UnwrapPromise<ReturnType<typeof api.DepartmentTreeData>>['data']

export const useDeptStore = defineStore('dept', () => {
  const list = ref<any>()

  const treeList = ref<any[]>([])

  const structuredList = (
    // eslint-disable-next-line @typescript-eslint/no-shadow
    list: any,
    parentId: string = '',
    parentList: any[] = [],
    level = 0,
    props = {
      childrenKey: 'childrenList',
      valueKey: 'deptId',
      labelKey: 'deptName',
    },
  ) => {
    const { valueKey, labelKey, childrenKey } = props
    const _list: any[] = []
    const _parentList = [...parentList]

    list.forEach((children: any) => {
      const item: any[] = [
        {
          label: children[labelKey],
          value: children[valueKey],
          parentId,
          parentList,
          level,
          show: level === 0,
          hasChildren: !!children[childrenKey]?.length,
          // isOpen: level === 0,
        },
      ]

      if (children[childrenKey]?.length) {
        _parentList.push(children[valueKey])
        item.push(
          // eslint-disable-next-line @typescript-eslint/no-unused-vars
          ...structuredList(
            children[childrenKey] || [],
            children[valueKey],
            _parentList,
            level + 1,
            props,
          ),
        )
      }
      _list.push(...item)
    })

    return _list
  }

  const init = async () => {
    const result = await api.DepartmentTreeData()
    treeList.value = structuredList([result.data])

    list.value = result.data || {}
  }

  return { list, treeList, init }
})
if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useDeptStore, import.meta.hot))
}
